package com.zz.webapp.common.Response;

import lombok.Data;

import java.io.Serializable;

/**
 * Created by Administrator on 2017/1/30.
 */
@Data
public class Response<T> implements Serializable {
    private static final long serialVersionUID = -6263133700441746486L;
    Code code = Code.SUCCESS;
    T data;

    public Response(){}
    public Response(Code code){
        this.code = code;
    }

    public boolean isSuccess(){
        return null != this.code && this.code.isSuccess();
    }

    public static<T> Response<T> ok(T data){
        Response<T> response = new Response<T>(new Code(true));
        response.data = data;
        return response;
    }

    public static<T> Response<T> ok(){
        return ok(null);
    }

    public static<T> Response<T> fail(String message){
        Response<T> response = new Response<T>(new Code(false));
        response.setData((T) Boolean.FALSE);
        response.code.setMessage(message);
        return response;
    }

    public Response<T> setResult(T result) {
        this.code = new Code();
        this.data = result;
        return this;
    }

    public T getResult() {
        return this.data;
    }

    public String getError() {
        return this.code.getMessage();
    }

    public Response<T> setError(String error) {
        this.code = Code.FAILURE;
        this.code.setMessage(error);
        return this;
    }

    public Response<T> setSuccess (boolean success) {
        if (success) {
            this.setCode(new Code(true));
        }else {
            this.setCode(new Code(false));
        }
        return this;
    }

}
